<?php
/**
 * Smarty视图
 * 
 * 通过Smarty模板引擎绘制视图。
 * 
 * @author Leo Ning <leo.ning@like18.com> 2010-11-14 12:25
 * @version 1.0
 * @since 1.0
 * @copyright 2008-2011 LIKE18 INC.
 * @package view
 */
class SmartyView extends View {
	const EXT = '.tpl';
	/**
	 * 绘制
	 *
	 * @param Action $action        	
	 * @param string $module        	
	 * @return string
	 */
	public function render($action, $module) {
		global $__smarty, $__global;
		$this->tpl = $module . DS . 'views' . DS . $this->tpl;
		$_tpl_path = $__global ['is_plugin_action'] ? PLUGIN_PATH : MODULE_PATH;		
		$tpl = $_tpl_path . $this->tpl . SmartyView::EXT;
		$data = $this->data;
		if (is_file ( $tpl )) {
			$__smarty = new Smarty ();
			$__smarty->addPluginsDir ( CORE_PLUGIN_PATH . 'smarty' );
			$__smarty->template_dir = $_tpl_path; // 模板目录
			$tpl = str_replace ( DS, '/', $this->tpl );
			$tpl = explode ( '/', $tpl );
			array_pop ( $tpl );
			$sub = implode ( DS, $tpl );
			$__smarty->compile_dir = TMP_PATH . 'tpls_c' . DS . ($__global ['is_plugin_action'] ?'plugins':'modules') . DS . $sub; // 模板编译目录
			$__smarty->cache_dir = TMP_PATH . 'tpls_cache' . DS . ($__global ['is_plugin_action'] ?'plugins':'modules') . DS . $sub; // 模板缓存目录
			$__smarty->_dir_perms = 0775;
			$__smarty = apply_filter ( 'init_smarty_view_engine', $__smarty );
			if (DEBUG) {
				$__smarty->force_compile = true;
			}
			if (is_array ( $data ) && ! empty ( $data )) {
				$data = array_merge ( $__global, $data );
				foreach ( $data as $n => $v ) {
					$__smarty->assign ( $n, $v ); // 变量
				}
			}
			$__smarty->assign ( '_C', $action ); // 变量
			return $__smarty->fetch ( $this->tpl . SmartyView::EXT );
		} else {
			Response::error ( 'The view template ' . $tpl . ' is not found', 404 );
		}
	}
	
	public function setHeader() {
		@header ( 'Content-Type: text/html' );
	}
}